package org.yx.service.smfr.save_process_path;

import org.dbist.dml.Query;
import org.yx.exception.BizException;
import org.yx.models.SmfrProPth;
import org.yx.models.SmfrPthOpr;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 保存工艺路线
 * @author zxw
 * @since 2018/03/30
**/
public class SmfrSaveProcessPathService extends BaseService {
	public SmfrSaveProcessPathOut saveProcessPath(SmfrSaveProcessPathIn in) throws Exception {
		if (StrUtil.isBlank(in.getPathCode())) {
			throw new BizException("SYS-0004", new FieldMap("parameter", "pathCode"));
		}

		SmfrProPth oldPath = selectWithPk(SmfrProPth.class, in.getUserOrgCode(), in.getPathCode());
		if (oldPath != null) {
			if (oldPath.getPathStatus() == 'D') {
				throw new BizException("SMFR-0002", new FieldMap("pathCode", oldPath.getPathCode()));
			}
			if (oldPath.getPathStatus() == 'H') {
				throw new BizException("SMFR-0003", new FieldMap("pathCode", oldPath.getPathCode()));
			}
		}

		SmfrProPth path = new SmfrProPth();
		copyProperties(in, path);
		path.setOrgCode(in.getUserOrgCode());
		path.setPathStatus('N');

		upsert(path);

		if (CollUtil.isNotEmpty(in.getOperList())) {
			for (int i = 0; i < in.getOperList().size(); i++) {
				SmfrPthOpr opr = in.getOperList().get(i);
				if (opr.getSeqNum() == null) {
					opr.setSeqNum(i + 1);
				}
				if (StrUtil.isBlank(opr.getOper())) {
					throw new BizException("SYS-0004", new FieldMap("parameter", "operList.oper"));
				}

				opr.setOrgCode(path.getOrgCode());
				opr.setPathCode(path.getPathCode());
				opr.setStatus('N');
			}
			
			Query query = new Query();
			query.addFilter("orgCode", path.getOrgCode());
			query.addFilter("pathCode", path.getPathCode());
			deleteList(SmfrPthOpr.class, query);
			insertBatch(in.getOperList());
		}

		SmfrSaveProcessPathOut out = new SmfrSaveProcessPathOut();

		return out;
	}
}